axios.defaults.baseURL = 'http://ajax-api.itheima.net'

const tb = document.querySelector('#tb')

const bookname = document.querySelector('[name="bookname"]')
const author = document.querySelector('[name="author"]')
const publisher = document.querySelector('[name="publisher"]')
// 获取内容列表
const bookList = () => {
  console.log(1);
  axios({
    url:'/api/books',
  }).then(res => {
    console.log(res);
    let num = ''
    res.data.data.forEach((item) => {
      // console.log(item);
      const { id, bookname, author, publisher } = item
      num += `
      <tr>
      <td>${id}</td>
      <td>${bookname}</td>
      <td>${author}</td>
      <td>${publisher}</td>
    </tr> -->
     <a href="javescript" data-id=${id}>删除</a>
      `
    })
    console.log(num);
    tb.innerHTML=num
  })
}
bookList() //记得调用

// 新增图书
const data= document.querySelector('#bookForm').addEventListener('submit', (e)=> {
  // 阻止默认提交
  e.preventDefault()

  if (!bookname.value || !author.value || !publisher.value)
    return alert('好好输入')
  
    const data = serialize(document.querySelector('#bookForm'), { hash: true })
  axios({
    url: '/api/books',
    method: 'post',
    data
  }).then(res => {
    if (res.status === 201) {
      alert('添加成功')
    }
    // 清空
    document.querySelector('#bookForm').reset()
    // 在获取列表
    bookList()
  })
})

// 删除
tb.addEventListener('click', (e) => {
  if (e.target.tagName === 'A') {
    const id = e.target.dataset.id
    axios({

      // /api/books/:id=''  文档里要求的写法 :id=''  写成  ${id}
      url: `/api/books/${id}`,
      method: 'delete',
    }).then((res) => {
      // console.log(res);
      alert('删除成功')
      // 获取
      bookList()
    })
  }
})